package dao;

import application.exceptions.ItemNotFoundException;
import mappings.PhotoComposition;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import utils.HibernateUtil;

@SuppressWarnings("JpaQlInspection")
public class PhotoCompositionDao
{
    private static SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

    public PhotoComposition addPhoto(String name, String url)
    {
        PhotoComposition photo = new PhotoComposition();
        photo.setName(name);
        photo.setUrl(url);

        org.hibernate.classic.Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();

        session.save(photo);

        tx.commit();
        session.close();

        return photo;
    }

    public PhotoComposition editPhoto(Integer id, PhotoComposition photo) throws ItemNotFoundException
    {
        org.hibernate.classic.Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();

        PhotoComposition photoToEdit = (PhotoComposition) session.get(PhotoComposition.class, id);

        if(photoToEdit == null)
        {
            tx.rollback();
            session.close();
            throw new ItemNotFoundException();
        }

        photoToEdit.setName(photo.getName());
        photoToEdit.setUrl(photo.getUrl());
        session.update(photoToEdit);
        tx.commit();
        session.close();

        return photoToEdit;
    }

    public void deletePhoto(Integer id) throws ItemNotFoundException
    {
        org.hibernate.classic.Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();

        int affectedRows = session.createQuery("delete PhotoComposition where id = :id")
                .setParameter("id", id)
                .executeUpdate();

        if(affectedRows == 0)
        {
            tx.rollback();
            session.close();
            throw new ItemNotFoundException();
        }

        tx.commit();
        session.close();
    }
}
